package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import entity.User;
import service.UserService;
import util.ResponseMessage;

@Controller
@RequestMapping("/Account")
public class AccountController {

	@Autowired
	private UserService userService;

	@RequestMapping("/")
	public String index() {
		return "account/login";
	}

	@RequestMapping("/Welcome")
	public String welcome() {
		return "account/welcome";
	}

	@CrossOrigin(allowCredentials="true")
	@ResponseBody
	@PostMapping("/Login")
	public ResponseMessage login(String userId,String password,HttpServletRequest request) {
		User user = new User();
		user.setUserId(userId);
		user.setPassWord(password);
		boolean flag = userService.login(user);
		if (flag) {
            HttpSession session=request.getSession();
            session.setAttribute("user", user);
			return new ResponseMessage(ResponseMessage.SUCCESS,"登录成功");
		} else {
			return new ResponseMessage(ResponseMessage.ERROR,"用户名或密码错误");
		}
	}

	@CrossOrigin(allowCredentials="true")
	@ResponseBody
	@PostMapping("/Register")
	public ResponseMessage register(String userId,String password,String icon,String name,int type) {
        boolean flag = userService.findUser(userId);
        if (flag) {
            return new ResponseMessage(ResponseMessage.ERROR, "手机号已被注册，注册失败");
        }
        User user = new User();
        user.setUserId(userId);
        user.setPassWord(password);
        user.setName(name);
        user.setType(type);
        boolean add_flag = userService.register(user);
        return new ResponseMessage(ResponseMessage.SUCCESS, "用户注册成功");
    }

} // end class
